var snake = new Snake();
snake.head = null;    //蛇头，用于记录蛇头的相关信息
snake.tail = null;    //蛇尾，用于记录蛇尾的相关信息

var directionNum = {
    left: {
        x: -1,
        y: 0
    },
    right: {
        x: 1,
        y: 0,
    },
    top: {
        x: 0,
        y: -1,
    },
    bottom: {
        x: 0,
        y: 1
    }
}

snake.init = function () {
    var snakeHead = SquareFactory.create('SnakeHead', 3, 1, 'deeppink');
    var snakeBody1 = SquareFactory.create('SnakeBody', 2, 1, 'green');
    var snakeBody2 = SquareFactory.create('SnakeBody', 1, 1, 'green');

    snake.head = snakeHead;
    snake.tail = snakeBody2;

    ground.remove(snakeHead.x, snakeHead.y); //先删除蛇头位置的地板方块
    ground.append(snakeHead);   //再添加蛇头（一个位置只能有一个方块）

    ground.remove(snakeBody1.x, snakeBody1.y);   //先删除蛇身位置的地板方块
    ground.append(snakeBody1);  //再添加蛇身（一个位置只能有一个方块）

    ground.remove(snakeBody2.x, snakeBody2.y);   //先删除蛇身位置的地板方块
    ground.append(snakeBody2);  //再添加蛇身（一个位置只能有一个方块）

    //链表
    snakeHead.next = snakeBody1;
    snakeHead.last = null;

    snakeBody1.next = snakeBody2;
    snakeBody1.last = snakeHead;

    snakeBody2.next = null;
    snakeBody2.last = snakeBody1;

    this.direction = directionNum.right;  //蛇走的方向，一上来先给蛇一个默认的方向
};

//这个方法用于获取蛇头走到的下一个方块
snake.getCollideSquare = function () {
    var nextSquare = ground.squareTable[snake.head.y + this.direction.y][snake.head.x + this.direction.x];
    //console.log(nextSquare);

    this.collideMethod[nextSquare.collide](nextSquare);
}

//蛇头与下一个方块碰撞后的处理方法
snake.collideMethod = {
    move: function (square,boolean) {
        //创建了一个新的蛇身
        var newBody = SquareFactory.create('SnakeBody', snake.head.x, snake.head.y, 'green');

        //更新链表的关系（注意：这里没有body1,body2,只有head，所以关系只能从head身上找）
		newBody.next = snake.head.next;	//新身体的左边改成body1，由于没有body1（body1=snake.head.next;）
		newBody.last = null;			//新身体的右边为null
		newBody.next.last = newBody;	//body1的右侧为新身体

        ground.remove(snake.head.x, snake.head.y);
        ground.append(newBody);

        //创建了一个新的蛇头
        var newHead = SquareFactory.create('SnakeHead', square.x, square.y, 'deeppink');

        //更新链表的关系
		newHead.next = newBody;	//蛇头左边是新身体
		newHead.last = null;	//蛇头右边啥也没有
		newBody.last = newHead;	//新身体的右边是蛇头

        ground.remove(square.x, square.y);
        ground.append(newHead);

        snake.head = newHead;   //更新一下蛇头
        
        //删除最后一节身体
        if(!boolean){ 	//这个条件成立说明要继续走（需要删除最后一节身体） 
           var newFloor=SquareFactory.create('Floor',snake.tail.x,snake.tail.y,'grey'); //在蛇尾的位置创建一个地板
           ground.remove(snake.tail.x,snake.tail.y);
           ground.append(newFloor);
           snake.tail=snake.tail.last;  //更新蛇尾
        }
    },
    eat: function (square) {
        this.move(square,true);
        game.score++;
        createFood();
    },
    die: function () {
        game.over();
    }
}

// snake.init();
//snake.getCollideSquare();